package chzhenjia.learn.androidcode.four;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

import chzhenjia.learn.androidcode.R;

public class GetAndPostMethodActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etPassword;
    private EditText etUsername;
    private EditText etCaptcha;
    private ImageButton ibtnCaptcha;
    private String sessionId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_and_post_method);

        etPassword = (EditText) findViewById(R.id.et_password);
        etUsername = (EditText) findViewById(R.id.et_username);
        etCaptcha = (EditText) findViewById(R.id.et_captcha);
        Button btnPostLogin = (Button) findViewById(R.id.btn_post_login);
        Button btnGetLogin = (Button) findViewById(R.id.btn_get_login);
        btnGetLogin.setOnClickListener(this);
        btnPostLogin.setOnClickListener(this);

        ibtnCaptcha = (ImageButton) findViewById(R.id.ibtn_captcha);
        ibtnCaptcha.setOnClickListener(this);
        changeCaptcha();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_get_login:
                getLogin();
                break;
            case R.id.btn_post_login:
                postLogin();
                break;
            case R.id.ibtn_captcha:
                changeCaptcha();
                break;
        }
    }

    /**
     * 改变验证码
     */
    private void changeCaptcha() {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams("date", new Date().getTime());
        if (sessionId != null) {
            client.addHeader("Cookie", sessionId);
        }
        client.get("http://169.254.198.156/jboa/captcha", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (sessionId == null) {
                    for (Header header : headers) {
                        if (header.getName().equals("Set-Cookie")) {
                            String cookie = header.getValue();
                            sessionId = cookie.substring(0, cookie.contains(";") ? cookie.indexOf(";") : cookie.length() - 1);
                        }
                    }
                }
                ibtnCaptcha.setImageBitmap(BitmapFactory.decodeByteArray(responseBody, 0, responseBody.length));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(GetAndPostMethodActivity.this, "访问失败错误码为=" + statusCode, Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void postLogin() {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("password", getEditTextContent(etPassword));
        params.put("username", getEditTextContent(etUsername));
        params.put("captcha", getEditTextContent(etCaptcha));
        client.addHeader("Cookie", sessionId);
        client.post("http://169.254.198.156/jboa/sign/in", params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject json) {
                try {
                    Toast.makeText(GetAndPostMethodActivity.this, json.getBoolean("status") ? "POST登陆成功" : "POST" + json.getString("msg"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Toast.makeText(GetAndPostMethodActivity.this, "访问失败错误码为=" + statusCode, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getLogin() {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("password", getEditTextContent(etPassword));
        params.put("username", getEditTextContent(etUsername));
        params.put("captcha", getEditTextContent(etCaptcha));
        client.addHeader("Cookie", sessionId);
        client.get("http://169.254.198.156/jboa/sign/in", params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject json) {
                try {
                    Toast.makeText(GetAndPostMethodActivity.this, json.getBoolean("status") ? "Get登陆成功" : "Post" + json.getString("msg"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private String getEditTextContent(EditText et) {
        return et.getText().toString().trim();
    }
}
